import {StyleSheet, Text, View} from 'react-native'
import React, {Component} from 'react'
import LabelCell from "../../component/page/primary/payWay/labelCell";
import {default as styles, padding} from "../../style";
import {AlertButtonStyle, alertProxy} from "../../component/common/AlertProxy";
import * as WeChat from 'react-native-wechat'
import {Store} from "../../store";
import {inject, observer} from "mobx-react/native";
import {pay} from 'react-native-alipay';
import {Actions} from "react-native-router-flux";
import {afterAnimation} from "../../util";
import toast from "../../component/common/ToastProxy";

interface PayWayProps extends Store {

}

interface PayWayState {

}

@inject("order")
@observer
export default class PayWay extends Component<PayWayProps, PayWayState> {

    constructor(props: PayWayProps) {
        super(props);
    }

    get isFree() {
        return !this.props.order.selectedOrder.actuallyPaid;
    }

    async componentDidMount() {
        if (this.isFree) {
            await this.props.order.freePayNotify();
            alertProxy('提示', '购买成功！\r\n本次支付全由积分抵扣！', [{
                text: "知道了", onPress: () => {
                    Actions.popTo("_Index");
                }
            }]);
        }
    }

    render() {
        const payWayListConfig = [
            {
                icon: {
                    name: "zhifubaozhifu",
                    color: "#3DA7F5",
                    size: 20
                },
                label: {
                    text: "支付宝支付"
                },
                onPress: async () => {
                    const payInfo = await this.props.order.payOrder("alipay");
                    const result = await pay(payInfo, true);
                    if (+result["resultStatus"] === 9000) {
                        afterAnimation(async () => {
                            alertProxy('提示', '支付成功', [{
                                text: "知道了", onPress: () => {
                                    Actions.popTo("_Index");
                                }
                            }]);
                        });
                    } else {
                        afterAnimation(async () => {
                            alertProxy('提示', '已取消支付,请记得支付哦~', [{
                                text: "知道了", onPress: () => {
                                    Actions.popTo("_Index");
                                }, style: AlertButtonStyle.destructive
                            }]);
                        });

                    }

                }
            },
            {
                icon: {
                    name: "weixinzhifu",
                    color: "#41B035",
                    size: 20
                },
                label: {
                    text: "微信支付"
                },
                onPress: async () => {
                    try {
                        const payInfo = await this.props.order.payOrder("wechat");
                        const result = await WeChat.pay(
                            {
                                partnerId: payInfo.mch_id,  // 商家向财付通申请的商家id
                                prepayId: payInfo.prepay_id,   // 预支付订单
                                nonceStr: payInfo.nonce_str,   // 随机串，防重发
                                timeStamp: payInfo.timeStamp,  // 时间戳，防重发
                                package: 'Sign=WXPay',    // 商家根据财付通文档填写的数据和签名
                                sign: payInfo.sign        // 商家根据微信开放平台文档对数据做的签名
                            }
                        );
                        console.log(result);
                        console.log(+result["errCode"] === 0);
                        if (+result["errCode"] === 0) {
                            toast("支付成功！", function () {
                                afterAnimation(async () => {
                                    Actions.popTo("_Index");
                                });
                            });
                        } else {
                            toast("已取消支付,请记得支付哦~！", function () {
                                afterAnimation(async () => {
                                    Actions.popTo("_Index");
                                });
                            });
                        }

                    }
                    catch (e) {
                        toast("已取消支付,请记得支付哦~！", function () {
                            afterAnimation(async () => {
                                Actions.popTo("_Index");
                            });
                        });

                    }

                }
            }

        ];
        if (this.isFree) return <View/>
        return (<View style={style.container}>
            <View style={[{backgroundColor: "#fff"}, padding(18, 20)]}>
                <View style={[styles.flexDirectionRowNotFlex, styles.centerH]}>
                    <Text style={{fontSize: 12, color: "#666666"}}>付款金额：</Text>
                    <Text style={{
                        fontSize: 16,
                        color: "#333333",
                        fontWeight: "bold"
                    }}>￥{this.props.order.selectedOrder.actuallyPaid}</Text>
                </View>
                {this.deductionPriceScore > 0 ? <Text style={{
                    fontSize: 12,
                    marginTop: 5,
                    color: "#ff4a1c"
                }}>本次支付，积分抵扣 {this.deductionPriceScore} 元</Text> : null}
                <Text style={{fontSize: 12, marginTop: 5, color: "#FF9F00"}}>请尽快完成付款，2小时内未付款将自动取消订单</Text>
            </View>
            <View style={[padding(12, 20)]}>
                <Text style={{fontSize: 12, color: "#666666"}}>请选择支付方式</Text>
            </View>
            <View>
                {payWayListConfig.map((config, index) => {
                    return (<LabelCell style={{marginTop: 1}} {...config} key={index}/>)
                })}
            </View>
        </View>)
    }

    get deductionPriceScore() {
        //订单总金额（不包含运费） - 真实支付金额
        return this.props.order.selectedOrder.totalPrice - this.props.order.selectedOrder.actuallyPaid;
    }
}

const style = StyleSheet.create({
    container: {
        backgroundColor: "#F2F2F2"
    }
});

 